package yxy.game.pm2.command.mail;

import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.Currency;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.MailMessage;
import yxy.game.pm2.module.CurrencyHandle;
import yxy.game.pm2.module.mail.MailBean;

import java.util.Collection;

/** 邮件 邮件领取并删除 */
@MessageType(proto = Command.MailReceivedRemove, classtype = MailMessage.MailReceivedRemoveRequest.class)
public class CMD_MailReceivedRemove extends Command<MailMessage.MailReceivedRemoveRequest> {

	@Override
	public void execute(MessageSource messageSource, MailMessage.MailReceivedRemoveRequest request) {
		String playerCode = messageSource.getTag();
		String code = request.getCode();

		MailMessage.MailReceivedRemoveResponse.Builder response = MailMessage.MailReceivedRemoveResponse.newBuilder();

		MailBean mailBean = MailBean.get(playerCode, code);
		if (mailBean == null || mailBean.expired()) {
			send(messageSource, response, Result.MailExpired);// 邮件已过期
			return;
		}

		if (!mailBean.isRewarded() && mailBean.getRewards().size() > 0) {
			Collection<Currency> rewards = mailBean.getRewards();
			new CurrencyHandle().addCurrency(playerCode, mailBean.getReason(), rewards);
			response.addAllRewards(new CurrencyHandle().packItems(rewards));

		}
		MailBean.remove(playerCode, mailBean.getCode());

		response.setCode(mailBean.getCode());
		send(messageSource, response, Result.Success);

	}

	private void send(MessageSource messageSource, MailMessage.MailReceivedRemoveResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}